"use strict";

process.on("exit", () => {
  console.log();
});

if (!process.argv[2]) {
  throw new Error('[组件名]必填 - 请输入组件名')
}
if(!(/[a-zA-Z]+/g.test(process.argv[2]))) {
  throw new Error('[组件名]错误 - 请输入正确的组件名')
}
if(!process.argv[3]) {
  throw  new Error('[组件中文名]必填 - 请输入组件中文名')
}
if(!(/^(?:[\u4e00-\u9fa5·]+)$/g.test(process.argv[3]))) {
  throw  new Error('[组件中文名]错误 - 请输入正确的组件中文名')
}


const path = require("path");
const fs = require('fs');
const fileSave = require("file-save");
const uppercamelcase = require("uppercamelcase"); // 转驼峰
const componentname = process.argv[2]; // 获取到组件名
const chineseName = process.argv[3]; // 中文名字
const ComponentName = uppercamelcase(componentname); // 转驼峰ComponentName
const srcPath = path.resolve(__dirname, "packages", componentname); // 文件夹路径
const componentsPath = path.resolve(__dirname, './packages/components/index.js')  // 全局组件路径
const navPath = path.join(__dirname, './examples/nav.config.json') // nav路径
const mdPath = path.join(__dirname, './examples/docs/', `${componentname}.md`) // md路径
const cssPath = path.join(__dirname, './packages/theme-default/lib/', `${componentname}.less`) // css路径
const indexCssPath = path.join(__dirname, './packages/theme-default/lib/', `index.less`) // index css 路径


// 自动注册全局组件
function addComponent(path, importConent, ComponentName) {
  let content = fs.readFileSync(path, 'utf-8')
  let contentArr = content.split(/[\s]*\n[\s]*/)
  contentArr.splice(contentArr.indexOf('//'), 0, importConent)
  contentArr.splice(contentArr.indexOf(']'), 0, ComponentName + ',')
  fs.writeFileSync(path, contentArr.join('\r\n'))
}

// 驼峰转化为横线
function getKebabCase( str ) {
  return str.replace( /[A-Z]/g, function( i ) {
      return '-' + i.toLowerCase();
  })
}


// 创建文件夹
const Files = [
  {
    filename: "index.js",
    content: `import ${ComponentName} from './src/${componentname}';

/* istanbul ignore next */
${ComponentName}.install = function(Vue) {
  Vue.component(${ComponentName}.name, ${ComponentName});
};

export default ${ComponentName};`
  },
  {
    filename: `src/${componentname}.vue`,
    content: `<template>
  <div class="w-${componentname}">默认${chineseName}</div>
</template>

<script>
export default {
  name: 'W${ComponentName}'
};
</script>`
  }
];

const navConfigFile = require("./examples/nav.config.json");
let key = Object.keys(navConfigFile)[1]
navConfigFile[key][0].items.push({
    desc: `${ComponentName} ${chineseName}`,
    name: `${componentname}`,
    path: `/${componentname}`
});

const mdConent = `
# ${ComponentName} ${chineseName}
----
### 测试
<div class="demo-block">
   <w-${getKebabCase(componentname)}></w-${getKebabCase(componentname)}>
</div>

::: demo
\`\`\`html
<w-${getKebabCase(componentname)}></w-${getKebabCase(componentname)}>
\`\`\`
`

// 添加组件文件夹
Files.forEach(file => {
  fileSave(path.join(srcPath, file.filename)).write(file.content, "utf8").end("\n");
});

// 添加md文档
fileSave(mdPath).write(mdConent, 'utf8').end('\n');

  // 添加css
fileSave(cssPath).write(``, 'utf8').end('\n');

// 自动引入less文件
fs.appendFileSync(indexCssPath,`\n@import "${componentname}.less";`);

// 自动注册全局组件
addComponent(componentsPath, `import ${ComponentName} from '../${componentname}/index'`, ComponentName )

// 添加到 nav.config.json
fileSave(navPath).write(JSON.stringify(navConfigFile, null, '  '), 'utf8').end('\n');

console.log(`suceess create ---${componentname}`);
